//
//  BBNewsController.swift
//  BaoKanSwift
//
//  Created by uncle-R on 16/6/12.
//  Copyright © 2016年 uncle-R. All rights reserved.
//

import UIKit
import SDCycleScrollView
import MJRefresh

class BBNewsController: UIViewController,UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate {

    var bannerView :SDCycleScrollView?
    var tableView :UITableView?
    var pageIndex = 1
    var dataArr = [BBNewsModel]()
    
     // MARK: - /*******************cell重用标识符***********************/
    
    let NO_P_ID = "noPictureCell"
    let ONE_P_ID = "onePictureCell"
    let THREE_P_ID = "threePictureCell"
    
     // MARK: - /*****************************************************/
    
    var classID :Int? {
        didSet{
            if pageIndex == 1 {
                loadNewData()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        creatTableView()
        creatBannerView()
        
    
    }
     // MARK: - 轮播图
    func creatBannerView() {
        let bannerView = SDCycleScrollView(frame: CGRectMake(0, 0, UI_SCREEN_WIDTH, 150), delegate: self, placeholderImage: UIImage(named: "photoview_image_default_white"))
        bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight
        bannerView.pageDotColor = UIColor.whiteColor()
        bannerView.currentPageDotColor = UIColor.redColor()
        self.bannerView = bannerView
        tableView?.tableHeaderView = bannerView
    }
    
     // MARK: - TableView.
    func creatTableView() {
        
        let tableView = UITableView(frame: CGRectMake(0, 0, UI_SCREEN_WIDTH,self.view.height - 44 - 60), style: UITableViewStyle.Plain)
        self.tableView = tableView
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = UIView()
        tableView.estimatedRowHeight = 100 //预估行高
        //tableView.rowHeight = UITableViewAutomaticDimension iOS 8 才有
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        
        tableView.registerNib(UINib(nibName: "BBNoPictureCell", bundle: nil), forCellReuseIdentifier: NO_P_ID)
        tableView.registerNib(UINib(nibName: "BBOnePictureCell", bundle: nil), forCellReuseIdentifier: ONE_P_ID)
        tableView.registerNib(UINib(nibName: "BBThreePicCell", bundle: nil), forCellReuseIdentifier: THREE_P_ID)
        view.addSubview(tableView)
    }
    
    //---------------------------------------下拉刷新------------------------------------------
    func loadNewData(){
        loadData(pageIndex, refreshType: 0)
        
    }
    func loadMoreData(){
        
        loadData(pageIndex + 1, refreshType: 1)
    }
     // MARK: ----------------------------------------加载更多------------------------------------------
    /**
        加载新闻
     
     - parameter pageIndex:   页码
     - parameter refreshType: 0为下拉刷新.1为上拉加载更多
     */
    func loadData(pageIndex:Int,refreshType:Int){
        var params:[String : AnyObject]
        
        if classID == 10000 {
            params = [
                "pageIndex" : pageIndex
            ]
        } else {
            params = [
                "classid" : classID!,
                "pageIndex" : pageIndex
            ]
        }
        
        print(params)
        BBNetWorkTool.shareNetworkTool.get(ARTICLE_LIST, Param: params){
            (success,result,error)-> () in
            self.tableView!.mj_header.endRefreshing()
            self.tableView!.mj_footer.endRefreshing()
            
            if success == true{
                if let successResult = result{
                    
                    let data = successResult["data"][0].arrayValue.reverse()
                    let minId = self.dataArr.last?.id ?? "0"
                    let maxId = self.dataArr.first?.id ?? "0"
                    
                    var imgGroups = [String]()
                    var imgTitles = [String]()
                    for article in data {
                        var dict: [String : AnyObject] = [
                            "title" : article["title"].stringValue,          // 文章标题
                            "bclassid" : article["bclassid"].stringValue,    // 终极栏目id
                            "classid" : article["classid"].stringValue,      // 当前子分类id
                            "newstime" : article["newstime"].stringValue,    // 发布时间
                            "created_at" : article["created_at"].stringValue,// 创建文章时间戳
                            "username" : article["username"].stringValue,    // 用户名
                            "onclick" : article["onclick"].stringValue,      // 点击量
                            "smalltext" : article["smalltext"].stringValue,  // 简介
                            "id" : article["id"].stringValue,                // 文章id
                            "classname" : article["classname"].stringValue,  // 分类名称
                            "table" : article["table"].stringValue,          // 数据表名
                            "plnum" : article["plnum"].stringValue,          // 评论数量
                        ]
                        
                        // 判断是否有标题图片
                        if article["titlepic"].string != "" {
                            
                            var titlepicUrl = article["titlepic"].stringValue
                            // 判断url是否包含前缀
                            titlepicUrl = titlepicUrl.hasPrefix("http") ? titlepicUrl : "\(BASE_URL)\(titlepicUrl)"
                            dict["titlepic"] = titlepicUrl
                            
                            // 标题多图
                            let morepics = article["morepic"].array
                            if let morepic = morepics {
                                var morepicArray = [String]()
                                for picdict in morepic {
                                    var bigpicUrl = picdict["bigpic"].stringValue
                                    // 判断url是否包含前缀
                                    bigpicUrl = bigpicUrl.hasPrefix("http") ? bigpicUrl : "\(BASE_URL)\(bigpicUrl)"
                                    morepicArray.append(bigpicUrl)
                                }
                                dict["morepic"] = morepicArray
                                dict["piccount"] = 3
                            } else {
                                dict["piccount"] = 1
                            }
                        } else {
                            dict["piccount"] = 0
                        }
                        
                        // 字典转模型
                        let postModel = BBNewsModel(dict:dict)
                        
                       
                        if imgGroups.count < 3{
                            imgGroups.append(postModel.titlepic ?? "")
                            imgTitles.append(postModel.title ?? "")
                            print("jinlaile")
                        }
                        // 根据加载方式拼接数据
                        if refreshType == 0 {
                            if Int(maxId) < Int(postModel.id!) {
                                
                               // self.dataArr.removeAll(keepCapacity: false)
    
                                if self.dataArr.count >= 3 || postModel.piccount != 0 {
                                    self.dataArr.insert(postModel, atIndex: 0)
                                }
                            }
                        } else {
                            if Int(minId) > Int(postModel.id!) {
                                if self.dataArr.count >= 3 || postModel.piccount != 0 {
                                    self.dataArr.append(postModel)
                                }
                            }
                        }
                    }
                 
                    self.bannerView!.imageURLStringsGroup = imgGroups
                    self.bannerView!.titlesGroup = imgTitles
                    self.tableView!.reloadData()
                }
                else {
                    print("error:\(error)")
                }
            }
            
        }

        
    }
    
}


//MARK: Delegate   -----------------------  DataSource--------------------
extension BBNewsController{
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataArr.count >= 3 {
            return self.dataArr.count - 3
        } else {
            return 0
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        if self.dataArr.count >= 3{
            let newsModel = dataArr[indexPath.row+3]
            if newsModel.piccount == 0 { //无图新闻
                let cell = tableView.dequeueReusableCellWithIdentifier(NO_P_ID) as! BBNoPictureCell
                cell.model = newsModel
                return cell
            }
            else if newsModel.piccount == 1{ //一张图新闻.
                let cell = tableView.dequeueReusableCellWithIdentifier(ONE_P_ID) as! BBOnePictureCell
                cell.model = newsModel
                return cell
            }
            else {
                let cell = tableView.dequeueReusableCellWithIdentifier(THREE_P_ID) as! BBThreePicCell
                cell.model = newsModel
                return cell
            }
            
        }
        
        return UITableViewCell()//-->>默认返回一个cell (一般调用不了)
    }

    //-----------------------------------------------TableView's Delegate-------------------------------------------
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        if self.dataArr.count > 3{
            let model = self.dataArr[indexPath.row + 3] //出去 轮播图 从第一条新闻开始算
            
            if model.rowHeight != 0.0 {
                return model.rowHeight
            }
            
            switch model.piccount {
            case 0:
                //取出cell 用于计算行高 并储存起来
                let cell = tableView.dequeueReusableCellWithIdentifier(NO_P_ID) as! BBNoPictureCell
                let height = cell.getRowHeight(model)
              return height
            case 1:
                //单张图片固定高度
                return 100
            case 3:
                let cell = tableView.dequeueReusableCellWithIdentifier(THREE_P_ID) as! BBThreePicCell
                let height = cell.getRowHeight(model)
                return height
                
            default:
                return 100;
            }
        
        }
        return 100
    }
    
}
